package org.hishenframework.core.security;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserDetailService implements UserDetailsService{

	@Resource
	private SecurityService securityService;
	
	@Override
	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException {
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		GrantedAuthority grantedAuthority = null;
		Map<String, Object> userTemp = securityService.getUserByUsername(arg0);
		if(userTemp == null){
			throw new UsernameNotFoundException("Username Not Found");
		}
		List<Map<String, Object>> rolesTemp = securityService.getRolesByUsername(arg0);
		Iterator<Map<String, Object>> iteratorOfrolesTemp = rolesTemp.iterator();
		while(iteratorOfrolesTemp.hasNext()){
			String role = (String) iteratorOfrolesTemp.next().get("role");
			grantedAuthority = new SimpleGrantedAuthority(role);
			grantedAuthorities.add(grantedAuthority);
		}
		User user = new User((String)userTemp.get("username"), (String)userTemp.get("password"), (Boolean)userTemp.get("enabled"), true, true, true, grantedAuthorities);
		
		return user;
	}

}
